package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.ruoyi.common.config.DroolsConfig;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.opio.util.ExampleBase;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.domain.SysDangerUnit;
import com.ruoyi.system.domain.vo.SysDangerPointVO;
import com.ruoyi.system.entity.SysDangerPoint;
import com.ruoyi.system.entity.SysMonitor;
import com.ruoyi.system.entity.SysRemind;
import com.ruoyi.system.mapper.SysDangerPointMapper;
import com.ruoyi.system.mapper.SysDangerUnitMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.SysDangerPointService;
import com.ruoyi.system.service.SysMonitorService;
import com.ruoyi.system.service.SysRemindService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.kie.api.builder.Message;
import org.kie.api.builder.Results;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.utils.KieHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (SysDangerPoint)表服务实现类
 *
 * @author makejava
 * @since 2022-11-22 09:55:00
 */
@Service("sysDangerPointService")
public class SysDangerPointServiceImpl implements SysDangerPointService {

    @Resource
    private KieContainer kieContainer;

    @Resource
    private SysDangerPointMapper sysDangerPointMapper;

    @Autowired
    private Configuration configuration;

    @Autowired
    private DroolsConfig droolsConfig;

    @Resource
    private SysMonitorService sysMonitorService;

    @Autowired
    private SysDangerUnitMapper sysDangerUnitMapper;


    public static final String FileName = "/SysDangerPoint.drl";

    @Autowired
    private SysRemindService sysRemindService;
    @Resource
    private EnterpriseWXServiceImpl enterpriseWXService;
    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public SysDangerPoint queryById(Integer id) {
        return this.sysDangerPointMapper.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param sysDangerPoint 筛选条件
     * @return 查询结果
     */
    @Override
    public List<SysDangerPoint> queryByPage(SysDangerPoint sysDangerPoint) {
        return this.sysDangerPointMapper.queryAllByLimit(sysDangerPoint);
    }

    /**
     * 新增数据
     *
     * @param sysDangerPoint 实例对象
     * @return 实例对象
     */
    @Override
    public SysDangerPoint insert(SysDangerPoint sysDangerPoint) {
        this.sysDangerPointMapper.insert(sysDangerPoint);

        SysRole sysRole = new SysRole();
        sysRole.setRoleKey("qyzzts");
        List<SysUser> sysUsers = sysUserMapper.selectUserByRoleName(sysRole);
        if (!CollectionUtils.isEmpty(sysUsers)) {
            String stringBuffer = sysDangerPoint.getDangerName() + "发生异常。";

            for (SysUser sys : sysUsers) {
                sysRemindService.insert(SysRemind.TYPE_PROMPT, stringBuffer, sys.getUserId().intValue());
            }

            List<String> collect = sysUsers.stream().map(SysUser::getWxUserId).collect(Collectors.toList());
            EnterpriseWXServiceImpl.SendMessageRequest sendMessageRequest = new EnterpriseWXServiceImpl.SendMessageRequest();
            sendMessageRequest.setTouser(CollUtil.join(collect, "|"));
            sendMessageRequest.setMsgtype("text");
            sendMessageRequest.setAgentid(1000319);
            EnterpriseWXServiceImpl.MessageContent messageContent = new EnterpriseWXServiceImpl.MessageContent();
            messageContent.setContent(stringBuffer);
            sendMessageRequest.setText(messageContent);
            enterpriseWXService.pushMessage(sendMessageRequest);
        }

        try {
            this.createDroolsFile();
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        }
        return sysDangerPoint;
    }

    /**
     * 修改数据
     *
     * @param sysDangerPoint 实例对象
     * @return 实例对象
     */
    @Override
    public SysDangerPoint update(SysDangerPoint sysDangerPoint) {
        this.sysDangerPointMapper.update(sysDangerPoint);
        try {
            this.createDroolsFile();
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        }
        return this.queryById(sysDangerPoint.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.sysDangerPointMapper.deleteById(id) > 0;
    }

    @Override
    public List<SysDangerPoint> queryAll() {
        return sysDangerPointMapper.queryAll();
    }

    @Override
    public String importExcel(List<SysDangerPoint> sysDangerPoints, boolean updateSupport, String operName) {
        if (StringUtils.isNull(sysDangerPoints) || sysDangerPoints.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        for (SysDangerPoint sysDangerPoint : sysDangerPoints) {
            // 根据单元名称获取单元ID
            String unitName = sysDangerPoint.getUnitName();
            // 插入单元的部门名称、处置方案、联动监控点
            SysDangerUnit sysDangerUnit = sysDangerUnitMapper.getByName(unitName);
            if (sysDangerUnit != null) {
                sysDangerPoint.setUnitId(sysDangerUnit.getId());
                sysDangerPoint.setDeptName(sysDangerUnit.getDeptName());
                sysDangerPoint.setDeptId(sysDangerUnit.getDeptId());
                if (StringUtils.isNotEmpty(sysDangerUnit.getPlanId())) {
                    sysDangerPoint.setPlanId(Integer.valueOf(sysDangerUnit.getPlanId()));
                    sysDangerPoint.setPlanName(sysDangerUnit.getPlanName());
                }
                sysDangerPoint.setMonitorPointCode(sysDangerUnit.getMonitorPointId());
            }
        }
        sysDangerPointMapper.insertBatch(sysDangerPoints);
        return "成功";
    }

    public void reload() {
        KieHelper kieHelper = new KieHelper();
        kieHelper.addContent(FileUtil.readString(droolsConfig.getUrl() + FileName, Charset.forName("utf-8")), ResourceType.DRL);
        Results results = kieHelper.verify();
        if (results.hasMessages(Message.Level.ERROR)) {
            System.out.println(results.getMessages());
            throw new IllegalStateException("### errors ###");
        }
        kieContainer = kieHelper.getKieContainer();
        System.out.println("刷新文件");
    }

    // 生成规则文件
    @Async
    public void createDroolsFile() throws IOException, TemplateException {
        List<SysDangerPointVO> sysDangerPointVOS = getDate();
        Template template = configuration.getTemplate("SysDangerPoint.ftl");
        Map<String, Object> map = new HashMap<>();
        map.put("SysDangerPointVOList", sysDangerPointVOS);
        FileOutputStream file = new FileOutputStream(droolsConfig.getUrl() + FileName);
        OutputStreamWriter out = new OutputStreamWriter(file, "utf-8");
        template.process(map, out);
        out.close();
        System.out.println("success");
        this.reload();
    }

    // 定时查询实时数据，是否达到报警条件
    @Scheduled(cron = "0/60 * * * * ?")
    public void ScheduledDataAlert() {
        List<SysDangerPointVO> sysDangerPointVOS = getDate();
        Map<String, Object> map = ExampleBase.toResult();
        if (CollUtil.isNotEmpty(map)) {
            sysDangerPointVOS.forEach(i -> {
                Object o = map.get(i.getDatabaseBitNumber());
                i.setAv(StringUtils.isEmpty(o.toString()) ? 0 : Double.valueOf(o.toString()));
                // 调用规则引擎判断
                KieSession kieSession = kieContainer.newKieSession();
                kieSession.insert(i);
                kieSession.fireAllRules();
                kieSession.dispose();
                if (i.getAlert() == 1) {
                    SysMonitor query = sysMonitorService.queryByDataBase(i.getDatabaseBitNumber());
                    if (query == null || !StringUtils.isEmpty(query.getMonitorEndTime())) {
                        if (query != null) {
                            if (!query.getMonitorLevel().equals(i.getAlertType())) {
                                query.setMonitorEndTime(DateUtil.now());
                                query.setMonitorState("已恢复");
                                sysMonitorService.update(query);
                            }
                        }
                        SysMonitor sysMonitor = new SysMonitor();
                        sysMonitor.setMonitorType("重大危险源");
                        sysMonitor.setMonitorName(i.getDeviceName());
                        sysMonitor.setRealTimeDataAddress(i.getDatabaseBitNumber());
                        sysMonitor.setMonitorParam(i.getParam());
                        sysMonitor.setMonitorLevel(i.getAlertType());
                        sysMonitor.setMonitorValue(i.getAv().toString());
                        sysMonitor.setMonitorConfirmState("未确认");
                        sysMonitor.setMonitorState("未恢复");
                        sysMonitor.setMonitorStartTime(DateUtil.now());
                        sysMonitorService.insert(sysMonitor);
                    }
                } else {
                    SysMonitor query = sysMonitorService.queryByDataBase(i.getDatabaseBitNumber());
                    if (query != null && StringUtils.isEmpty(query.getMonitorEndTime())) {
                        query.setMonitorEndTime(DateUtil.now());
                        query.setMonitorState("已恢复");
                        sysMonitorService.update(query);
                    }
                }
            });
        }
    }

    // 定时查询实时数据，是否达到报警条件
    @Scheduled(cron = "0/60 * * * * ?")
    public void ScheduledRestoreMonitorAlert() {
        List<SysMonitor> monitors = sysMonitorService.queryByDataAddress();
        monitors.forEach(i -> {
            String monitorStartTime = i.getMonitorStartTime();
            String monitorEndTime = i.getMonitorEndTime();
            if (StringUtils.isEmpty(monitorEndTime)) {
                DateTime monitorStart = DateUtil.parse(monitorStartTime);
                DateTime offsetMonitorStart = DateUtil.offsetMinute(monitorStart, 30);
                boolean after = DateUtil.date().isAfter(offsetMonitorStart);
                if (!after) {
                    i.setMonitorState("已超时");
                    sysMonitorService.update(i);
                }
            }
        });
    }

    public List<SysDangerPointVO> getDate() {
        List<SysDangerPoint> sysDangerPoints = sysDangerPointMapper.queryAll();
        List<SysDangerPointVO> sysDangerPointVOS = new ArrayList<>();
        for (SysDangerPoint i : sysDangerPoints) {
            if (i.getEnable().equals("停用")) {
                continue;
            }
            SysDangerPointVO sysDangerPointVO = new SysDangerPointVO();
            BeanUtils.copyBeanProp(sysDangerPointVO, i);
            // 低低低报
            String lowAndLow = i.getLowAndLow();
            sysDangerPointVO.setLowAndLow(StringUtils.isEmpty(lowAndLow) ? -1 : Double.valueOf(lowAndLow));
            // 低低报
            String playItLow = i.getPlayItLow();
            playItLow = StringUtils.isNotEmpty(playItLow) ? playItLow.replace("/", "") : playItLow;
            sysDangerPointVO.setPlayItLow(StringUtils.isEmpty(playItLow) ? -1 : Double.valueOf(playItLow));
            // 低报
            String lowQuota = i.getLowQuota();
            lowQuota = StringUtils.isNotEmpty(lowQuota) ? lowQuota.replace("/", "") : lowQuota;
            sysDangerPointVO.setLowQuota(StringUtils.isEmpty(lowQuota) ? -1 : Double.valueOf(lowQuota));
            // 高报
            String highQuota = i.getHighQuota();
            sysDangerPointVO.setHighQuota(StringUtils.isEmpty(highQuota) ? -1 : Double.valueOf(highQuota));
            // 高高报
            String highAndMighty = i.getHighAndMighty();
            sysDangerPointVO.setHighAndMighty(StringUtils.isEmpty(highAndMighty) ? -1 : Double.valueOf(highAndMighty));
            sysDangerPointVO.setAlert(0);
            sysDangerPointVOS.add(sysDangerPointVO);
        }
        return sysDangerPointVOS;
    }
}
